from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
import os
import sys
import subprocess
import platform

class CMakeExtension(Extension):
    def __init__(self, name, sourcedir=''):
        print("*" * 16)
        print(f"Creating CMakeExtension for {name}")
        Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)

class CMakeBuild(build_ext):
    def run(self):
        print("Starting CMakeBuild.run()")
        try:
            out = subprocess.check_output(['cmake', '--version'])
            print(f"Found CMake: {out.decode().strip()}")
        except OSError:
            raise RuntimeError("CMake must be installed to build the extension")

        for ext in self.extensions:
            self.build_extension(ext)

    def build_extension(self, ext):
        print(f"Building extension: {ext.name}")
        extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
        print(f"Extension directory: {extdir}")
        
        cmake_args = [
            f'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}',
            f'-DPYTHON_EXECUTABLE={sys.executable}'
        ]

        # 设置构建类型
        cfg = 'Debug' if self.debug else 'Release'
        build_args = ['--config', cfg]

        # 设置平台特定的参数
        if platform.system() == "Windows":
            cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)]
            if sys.maxsize > 2**32:
                cmake_args += ['-A', 'x64']
            build_args += ['--', '/m']
        else:
            cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]
            build_args += ['--', '-j2']

        # 创建构建目录
        build_temp = os.path.join(self.build_temp, ext.name)
        if not os.path.exists(build_temp):
            os.makedirs(build_temp)
        print(f"Build directory: {build_temp}")

        # 运行 CMake
        print(f"Running CMake in {build_temp}")
        print(f"CMake arguments: {cmake_args}")
        subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=build_temp)
        print(f"Building with arguments: {build_args}")
        subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=build_temp)

        # 检查输出文件
        if platform.system() == "Windows":
            ext_file = os.path.join(extdir, "my_c_string.pyd")
        else:
            ext_file = os.path.join(extdir, "my_c_string.so")
        
        if os.path.exists(ext_file):
            print(f"Successfully built extension at: {ext_file}")
        else:
            print(f"Warning: Extension file not found at: {ext_file}")

if __name__ == "__main__":
    setup(
        name='my_package',
        version='0.1',
        description='A sample Python package with C extension',
        author='Your Name',
        author_email='your.email@example.com',
        packages=find_packages(),
        ext_modules=[CMakeExtension('my_package.c_module.my_c_string', 'my_package/c_module')],
        cmdclass=dict(build_ext=CMakeBuild),
        python_requires='>=3.6',
    ) 